//
//  CTCContractDetailVC.m
//  ConsultantVersion
//
//  Created by 小龙 on 2017/4/18.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCContractDetailVC.h"
#import "FileOperation.h"
#import "CTCContractFileListVC.h"


@interface CTCContractDetailVC ()
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *requireLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (weak, nonatomic) IBOutlet UILabel *contractNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *downLoadBtn;
@property (weak, nonatomic) IBOutlet UIButton *uploadBtn;
@property (weak, nonatomic) IBOutlet UIButton *reciveBtn;

@property (weak, nonatomic) IBOutlet UIButton *refuseBtn;

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UILabel *passBackLabel;
@property (weak, nonatomic) IBOutlet UIButton *passBackBtn;

@property (weak, nonatomic) IBOutlet UIButton *reciveContractBtn;
@property (weak, nonatomic) IBOutlet UIButton *refuseContractBtn;

@property (weak, nonatomic) IBOutlet UIView *labelbackView;
/** <#strong属性注释#> */
@property (nonatomic, strong) CTCContractModel *contractModel;

@end

@implementation CTCContractDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"合同";
    
    [self getContractDetailData];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (self.isPush) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kReloadContractListListNotification object:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)getContractDetailData
{
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kContractDetail parameters:@{@"uuid":self.uuid} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"%@",responseObject);
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
            self.contractModel = [CTCContractModel yy_modelWithJSON:responseObject[@"data"]];
            [self setupUI];
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
             if ([responseObject[@"code"] integerValue]== 2) {
                 CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                 MPWeakSelf(self);
                 vc.loginSuccess = ^(){
                     [weakself getContractDetailData];
                 };
                 [self presentViewController:vc animated:YES completion:nil];
             }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}


- (void)setupUI
{
    [SDWebImageTool imageView:self.headImageView imageName:self.contractModel.headImg placeHolder:@"default-head" showProgress:NO];
    self.nameLabel.text = self.contractModel.bname;
    self.companyNameLabel.text = self.contractModel.companyName;
    self.requireLabel.text = self.contractModel.content;
    self.passBackLabel.text = @"";
    self.contractNameLabel.text = self.contractModel.buserFileName;
    self.dateLabel.text = [NSDate stringFromTimestamp:self.contractModel.comTime];
    /** 状态：状态: 0 初始 未接单 1 接单 2 拒单 3 已回传 4服务完成 5过期 */
    
    switch ([self.contractModel.status integerValue]) {
            case 0:
        {
            self.statusLabel.text = @"未接单";
            self.statusLabel.textColor = HEXCOLOR(0xfb6a31);
            self.labelbackView.hidden = NO;
            self.reciveBtn.hidden = NO;
            self.reciveBtn.backgroundColor = HEXCOLOR(0xfb6a31);
            self.refuseBtn.hidden = NO;
            
        }
            break;
            case 1:
        {
            self.statusLabel.text = @"已接单";
            self.statusLabel.textColor = HEXCOLOR(0x00c44e);
            self.labelbackView.hidden = NO;
            self.passBackBtn.hidden = NO;
            self.downLoadBtn.hidden = NO;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
            
        }
            break;
            
            case 2:
        {
            self.statusLabel.text = @"已拒单";
            self.statusLabel.textColor = HEXCOLOR(0x2079EF);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 3:
        {
            self.statusLabel.text = @"已回传合同";
            self.statusLabel.textColor = HEXCOLOR(0x00c44e);
            self.passBackLabel.text = @"咨询师已回传合同";
            self.contractNameLabel.text = self.contractModel.buserFileName;
            self.passBackLabel.text = @"";
            self.labelbackView.hidden = NO;
            self.downLoadBtn.hidden = YES;
            self.passBackBtn.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 4:
        {
            self.statusLabel.text = @"服务完成";
            self.statusLabel.textColor = HEXCOLOR(0xffa200);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
            case 5:
        {
            self.statusLabel.text = @"过期";
            self.statusLabel.textColor = HEXCOLOR(0xfb6a31);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
            
        default:
        {
            self.statusLabel.text = @"服务无响应";
            self.statusLabel.textColor = HEXCOLOR(0xcc100f);
            self.labelbackView.hidden = YES;
            self.reciveBtn.hidden = YES;
            self.refuseBtn.hidden = YES;
        }
            break;
    }
    
}


- (IBAction)downLoadBtnClick {
    
    NSString *url = [NSString stringWithFormat:@"%@%@" ,kDownloadUrl ,self.contractModel.buserFile];
    
    [MBProgressHUD showAnimationHUD];
    
    [RequestTool downLoadFile:url progress:^(NSProgress * _Nonnull downloadProgress) {
        DeLog(@"downloadProgress++++:%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showProgressWithMessage:@"下载中" progress:1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        DeLog(@"destination++++++:%@", response);
        NSString *documentPath = [FileOperation getDocumentsPath];
        NSString *docPath = [documentPath  stringByAppendingPathComponent:self.contractModel.buserFileName];
        DeLog(@"[NSURL fileURLWithPath:docPath]:%@",[NSURL fileURLWithPath:[docPath encodeURLString]]);
        return [NSURL fileURLWithPath:docPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nonnull filePath, NSError * _Nonnull error) {
        DeLog(@"completionHandler++++++:%@", response);
        DeLog(@"error++++++:%@", error);
        NSLog(@"%@",filePath);
        DeLog(@"[filePath absoluteString]:%@",[filePath absoluteString]);
        if (!error) {
            [MBProgressHUD showSuccessMessage:@"下载完成"];
        }
        else {
            if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
            }
            else {
                [MBProgressHUD showErrorMessage:@"服务器繁忙"];
            }
        }
    }];
    
}

- (IBAction)uploadBtnClick {
    
    CTCContractFileListVC *vc = [[CTCContractFileListVC alloc]init];
    CTCNavigationController *nav = [[CTCNavigationController alloc]initWithRootViewController:vc];
    
    MPWeakSelf(self);
    vc.selecteFileReturnBlock = ^(NSString *docFilePath){
//        NSArray *array = [docFilePath componentsSeparatedByString:@"/"];
//        weakself.fileNameLabel.text = [array lastObject];
//        weakself.docFilePath = docFilePath;
//        weakself.upLoadBtn.enabled = YES;
//        weakself.upLoadBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
//        [weakself.upLoadBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
        [weakself uploadBackFilePath:docFilePath];
    };
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)uploadBackFilePath:(NSString *)filePath
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"file"] = [NSData dataWithContentsOfFile:filePath];
    [MBProgressHUD showAnimationHUD];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", kUploadUrl, self.contractModel.uuid];
    
    [RequestTool postFile:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showProgressWithMessage:@"上传中" progress:1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount];
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DeLog(@"responseObject+++++:%@",responseObject);
//        [MBProgressHUD  hideHUD];
        
        if ([responseObject[@"code"] integerValue] == 1) {
            [MBProgressHUD showSuccessMessage:responseObject[@"des"]];
            self.statusLabel.text = @"已回传合同";
            self.statusLabel.textColor = HEXCOLOR(0x00c44e);
            self.uploadBtn.hidden = YES;
            self.downLoadBtn.hidden = YES;
            if (self.changeContractStatusBlock) {
                self.changeContractStatusBlock(CTCContractStatusTypeUploadBack);
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"des"] integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];

}

- (IBAction)reciveBtnClick {
    [self reciveOrder:YES];

}

- (void)reciveOrder:(BOOL)isRecive
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"uuid"] = self.contractModel.uuid;
    if (isRecive) {
        dic[@"type"] = @"1";
    } else {
        dic[@"type"] = @"2";
    }
    
    [MBProgressHUD showAnimationHUD];
    
    [RequestTool POST:kReciveOrderUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        
        if ([responseObject[@"code"] integerValue] == 1) {
            if (isRecive) {
                self.uploadBtn.hidden = NO;
                self.downLoadBtn.hidden = NO;
                self.reciveBtn.hidden = YES;
                self.refuseBtn.hidden = YES;
                self.statusLabel.text = @"已接单";
                self.statusLabel.textColor = HEXCOLOR(0x00c44e);
                if (self.changeContractStatusBlock) {
                    self.changeContractStatusBlock(CTCContractStatusTypeRecive);
                }
            } else {
                if (self.changeContractStatusBlock) {
                    self.changeContractStatusBlock(CTCContractStatusTypeRefuse);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"des"] integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];

}

- (IBAction)refuseBtnClick {
    
 [self reciveOrder:NO];}

@end
